<?php
namespace app\service\http\google\translation;

use app\service\http\google\GoogleApiClient;
use hunma\exception\ApiException;
use support\Log;

class HttpGoogleTranslation extends GoogleApiClient
{
    public function __construct()
    {
        $config['url'] = getenv('GOOGLE_API_TRANSLATION_URL','https://translation.googleapis.com');
        parent::__construct($config);
    }

    public function translate($data, array $options = [])
    {
        $resData = parent::get('/language/translate/v2', [
            'q' => $data['content'],
            'target' => $data['target'],
        ], [], $options);
        if(isset($resData['error'])) {
            throw new ApiException('Google Translation API error: ' . $resData['error']['message']);
        }

        if(!(isset($resData['data']['translations'][0]['translatedText']) && $resData['data']['translations'][0]['translatedText'])) {
            Log::channel('guzzlehttp')->error("Google翻译请求错误", $resData);
            throw new ApiException('翻译请求错误');

        }

        return $resData['data']['translations'][0];
    }
}